package com.xr.sunnyday.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.xr.sunnyday.dao.OrdersettingDao;
import com.xr.sunnyday.exception.SunnydayException;
import com.xr.sunnyday.pojo.OrderSetting;
import com.xr.sunnyday.service.OrdersettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrdersettingService.class)
public class OrdersettingServiceImp implements OrdersettingService {

    @Autowired
    private OrdersettingDao ordersettingDao;

    @Override
    @Transactional
    public void add(List<OrderSetting> orderSettingList)  throws SunnydayException {
        for (OrderSetting os: orderSettingList) {
            //根据时间查预约信息表，是否存在要插入的日期
            OrderSetting osInDb = ordersettingDao.findByOrderData(os.getOrderDate());
            //判断有没有这个日期
            if (null!=osInDb){
                //如果存在这个日期，如果已预约数量大于你要插入的可预约数量
                if (osInDb.getReservations()>os.getNumber()){
                    //抛异常
                    throw new SunnydayException(os.getOrderDate()+"中：已预约人数不能大于可预约人数");
                }else{
                    //数据合理，更新可预约人数，日期还是那个日期
                    ordersettingDao.updateNumber(os);
                }
            }else{
                ordersettingDao.add(os);
            }
        }
    }

    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String month) {
        //拼接每个月的起始日期
        String startDate = month+"-1";
        return ordersettingDao.getOrderSettingByMonth(startDate);
    }

    @Override
    public void editNumberByDate(OrderSetting os) {
        //根据时间查预约信息表，是否存在要插入的日期
        OrderSetting osInDb = ordersettingDao.findByOrderData(os.getOrderDate());
        //判断有没有这个日期
        if (null!=osInDb){
            //如果存在这个日期，如果已预约数量大于你要插入的可预约数量
            if (osInDb.getReservations()>os.getNumber()){
                //抛异常
                throw new SunnydayException(os.getOrderDate()+"中：已预约人数不能大于可预约人数");
            }else{
                //数据合理，更新可预约人数，日期还是那个日期
                ordersettingDao.updateNumber(os);
            }
        }else{
            ordersettingDao.add(os);
        }
    }
}
